package com.zuipin.controller;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.zuipin.entity.BalanceRecord;
import com.zuipin.entity.OrderInfo;
import com.zuipin.entity.SysUser;
import com.zuipin.enums.BalanceType;
import com.zuipin.enums.RecordSearchTime;
import com.zuipin.framework.annotation.Inject;
import com.zuipin.framework.annotation.Json;
import com.zuipin.framework.annotation.Valid;
import com.zuipin.framework.annotation.Valids;
import com.zuipin.framework.emuns.ErrorCode;
import com.zuipin.framework.exception.CustomException;
import com.zuipin.framework.result.PageResult;
import com.zuipin.framework.result.Result;
import com.zuipin.mapper.OrderInfoMapper;
import com.zuipin.service.IBalanceRecordService;
import com.zuipin.service.ISysUserService;
import com.zuipin.util.Pagination;
import com.zuipin.util.RegexUtils;
import com.zuipin.vo.BalanceAndRecordVo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

/**
 * @ClassName: BalanceRecordController
 * @author wuyicheng
 * @time 2017年3月27日下午4:RedisUtilTest00:56
 */
@Api(value = "余额变更记录", description = "余额变更记录-wuyicheng")
@RestController
@RequestMapping(value = "/member/balanceRecord")
public class BalanceRecordController {
	@Resource
	private IBalanceRecordService	balanceRecordService;
	@Resource
	private OrderInfoMapper			orderInfoMapper;
	
	@Resource
	private ISysUserService			sysUserService;
	
	private static Logger			log	= LoggerFactory.getLogger(BalanceRecordController.class);
	
	@Json(type = BalanceRecord.class, exclude = "remark")
	@RequestMapping(value = "/searchBalanceRecord", method = RequestMethod.GET)
	@ApiOperation(value = "查询余额变更记录-wuyicheng 备注：购物送积分（订单号：123456)  remark保存着购物送积分字段  describes保存 订单号字段  oddNumbers保存单号字段 ", notes = "查询余额变更记录-wuyicheng 备注：购物送积分（订单号：123456)  remark保存着购物送积分字段  describes保存 订单号字段  oddNumbers保存单号字段")
	@Valids({ @Valid(name = "memberId", minValue = 1), @Valid(name = "sysId", minValue = 1), @Valid(name = "balanceTypeChoose", regex = "1|2"),
			@Valid(name = "searchTime", required = true, regex = "THREE_MONTH_AGO|ONE_YEAR_AGO|ALL_AGO") })
	@ApiImplicitParams({ @ApiImplicitParam(name = "memberId", value = "会员ID", required = true, dataType = "long", paramType = "query"),
			@ApiImplicitParam(name = "sysId", value = "系统ID", required = true, dataType = "long", paramType = "query"),
			@ApiImplicitParam(name = "searchTime", value = "THREE_MONTH_AGO（三个月前）|ONE_YEAR_AGO（一年内）|ALL_AGO（全部时间）", required = true, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "balanceTypeChoose", value = "余额类型1全部充值记录  2充值记录", required = false, dataType = "integer", paramType = "query"),
			@ApiImplicitParam(name = "page.pageNumber", value = "页码", required = true, dataType = "integer", paramType = "query"),
			@ApiImplicitParam(name = "page.pageSize", value = "单页记录数", required = true, dataType = "integer", paramType = "query") })
	public PageResult<BalanceAndRecordVo> searchBalanceRecord(@RequestParam(required = false) Integer balanceTypeChoose, @RequestParam Long memberId, @RequestParam Long sysId,
			@RequestParam RecordSearchTime searchTime, @Inject @ApiIgnore Pagination page) {
		PageResult<BalanceAndRecordVo> result = new PageResult<>();
		BalanceRecord balanceRecord = new BalanceRecord();
		balanceRecord.setMemberId(memberId);
		balanceRecord.setSysId(sysId);
		balanceRecord.setSearchTime(searchTime.getKey());
		balanceRecord.setBalanceTypeChoose(balanceTypeChoose);
		
		BalanceAndRecordVo balanceAndRecordVo = new BalanceAndRecordVo();
		
		// 获取当前余额
		BigDecimal currentBalance = balanceRecordService.getCurrentBalance(memberId, sysId);
		
		List<BalanceRecord> list = balanceRecordService.findListByPage(balanceRecord, page);
		
		if (list != null && list.size() > 0) {
			// 填充订单ID给前台
			for (BalanceRecord br : list) {
				
				SysUser user = sysUserService.findById(br.getUpdateId());
				if (user != null) {
					br.setUpdateName(user.getRealName());
				}
				OrderInfo orderInfo = orderInfoMapper.findOrderInfoByOrderNo(br.getOddNumbers());
				if (orderInfo != null) {
					br.setOrderId(orderInfo.getId());
				}
			}
			
			balanceAndRecordVo.setRecords(list);
			balanceAndRecordVo.setBalance(currentBalance == null ? new BigDecimal(0.00) : currentBalance);
			
			result.setTotal_record(list.size());
			result.setData(balanceAndRecordVo);
		} else {
			result.setData(balanceAndRecordVo);
			result.setTotal_record(0);
		}
		result.setTotal_record(page.getTotalRecord());
		result.setErrorCode(ErrorCode.SUCCESS);
		return result;
	}
	
	// @Json(type = Result.class, exclude = "data,errorCode")
	@RequestMapping(value = "/updateBalance", method = RequestMethod.POST)
	@ApiOperation(value = "余额变更接口（废弃）-wuyicheng", notes = "余额变更接口（废弃）-wuyicheng")
	@Valids({ @Valid(name = "memberId", minValue = 1), @Valid(name = "sysId", minValue = 1), @Valid(name = "alterMoney", regex = RegexUtils.DOUBLE),
			@Valid(name = "balanceType", regex = "PAY|GIFT_CARD|REFUND|DRAW_GIVE|LOGIN_GIVE|REG_GIVE|BUY_USE") })
	@ApiImplicitParams({ @ApiImplicitParam(name = "memberId", value = "会员ID", required = true, dataType = "long", paramType = "query"),
			@ApiImplicitParam(name = "sysId", value = "系统ID", required = true, dataType = "long", paramType = "query"),
			@ApiImplicitParam(name = "createId", value = "创建人ID", required = false, dataType = "long", paramType = "query"),
			@ApiImplicitParam(name = "updateId", value = "修改人ID", required = false, dataType = "long", paramType = "query"),
			@ApiImplicitParam(name = "alterMoney", value = "修改的金额", required = true, dataType = "bigDecimal", paramType = "query"),
			@ApiImplicitParam(name = "balanceType", value = "余额类型:'PAY','GIFT_CARD','REFUND','DRAW_GIVE','LOGIN_GIVE','REG_GIVE','BUY_USE';充值方式:支付充值，礼品卡充值（醉品），退款转充值（醉品）,抽奖赠送，登陆赠送，注册赠送,购物使用充值", required = false, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "remark", value = "备注（微信充值|支付宝充值|块钱充值）", required = true, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "oddNumbers", value = "充值的单号", required = true, dataType = "string", paramType = "query") })
	
	public Result<Map<String, Object>> updateBalance(@RequestParam Long memberId, @RequestParam Long sysId, @RequestParam(required = false) Long createId,
			@RequestParam(required = false) Long updateId, @RequestParam BigDecimal alterMoney, @RequestParam BalanceType balanceType, @RequestParam(required = true) String remark,
			@RequestParam(required = true) String oddNumbers) throws CustomException {
		
		Result<Map<String, Object>> result = new Result<>();
		if (alterMoney != null && balanceType != null && BalanceType.PAY.equals(balanceType)) {
			if (alterMoney.compareTo(BigDecimal.ONE) < 0) {
				result.setErrorCode(ErrorCode.ILLEGAL_PARAM);
				result.setCnMessage("支付充值 ,金额只能大于1");
				return result;
			}
		}
		balanceRecordService.updateBalance(memberId, sysId, createId, updateId, alterMoney, BalanceType.PAY, remark, "单号", oddNumbers, BalanceRecord.IS_BUY_NO);
		result.setErrorCode(ErrorCode.SUCCESS);
		
		result.setData(null);
		return result;
	}
	
	// @Json(type = Result.class, exclude = "data,errorCode")
	@RequestMapping(value = "/toPay", method = RequestMethod.POST)
	@ApiOperation(value = "去充值接口-xujinding", notes = "去充值接口-xujinding")
	@Valids({ @Valid(name = "memberId", minValue = 1), //
			@Valid(name = "remark", regex = "微信充值|支付宝充值|快钱充值"), //
			@Valid(name = "sysId", minValue = 1), //
			@Valid(name = "oddNumbers", minLength = 1), //
			@Valid(name = "alterMoney", regex = RegexUtils.DOUBLE, minValue = 0.01, maxValue = 9999999) })
	@ApiImplicitParams({ @ApiImplicitParam(name = "memberId", value = "会员ID", required = true, dataType = "long", paramType = "query"),
			@ApiImplicitParam(name = "sysId", value = "系统ID", required = true, dataType = "long", paramType = "query"),
			@ApiImplicitParam(name = "alterMoney", value = "修改的金额", required = true, dataType = "bigDecimal", paramType = "query"),
			@ApiImplicitParam(name = "remark", value = "备注（微信充值|支付宝充值|快钱充值）", required = true, dataType = "string", paramType = "query"),
			@ApiImplicitParam(name = "oddNumbers", value = "充值的单号", required = true, dataType = "string", paramType = "query") })
	public Result<Map<String, Object>> updateBalance(@RequestParam Long memberId, @RequestParam Long sysId, @RequestParam BigDecimal alterMoney,
			@RequestParam(required = true) String remark, @RequestParam(required = true) String oddNumbers) throws CustomException {
		Result<Map<String, Object>> result = new Result<>();
		balanceRecordService.updateBalance(memberId, sysId, null, null, alterMoney, BalanceType.PAY, remark, "单号", oddNumbers, BalanceRecord.IS_BUY_NO);
		result.setErrorCode(ErrorCode.SUCCESS);
		result.setData(null);
		return result;
	}
	
	@RequestMapping(value = "/queryPayStatusByOddNumbers", method = RequestMethod.POST)
	@ApiOperation(value = "查询充值单号状态", notes = "查询充值单号状态,有记录返回success  没有返回对象不存在")
	@Valids({ @Valid(name = "sysId", minValue = 1), //
			@Valid(name = "oddNumbers", minLength = 1), })
	@ApiImplicitParams({ @ApiImplicitParam(name = "sysId", value = "系统ID", required = true, dataType = "long", paramType = "query"),
			@ApiImplicitParam(name = "oddNumbers", value = "充值的单号", required = true, dataType = "string", paramType = "query") })
	public Result<Map<String, Object>> queryPayStatusByOddNumbers(@RequestParam Long sysId, @RequestParam(required = true) String oddNumbers) throws CustomException {
		Result<Map<String, Object>> result = new Result<>();
		boolean res = balanceRecordService.queryPayStatusByOddNumbers(sysId, oddNumbers);
		if (res) {
			result.setErrorCode(ErrorCode.SUCCESS);
		} else {
			result.setErrorCode(ErrorCode.OBJECT_EXIST);
		}
		
		result.setData(null);
		return result;
	}
}
